package com.itheima.reggie.filter;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException, ServletException {
        HttpServletRequest rq = (HttpServletRequest) request;
        HttpServletResponse rp = (HttpServletResponse) response;
        //获取本次请求的URL
        String uri = rq.getRequestURI();

        //定义不需要处理的请求
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断当前页面是否拦截
        boolean check = check(loginUrls, uri);
        //不需要处理就直接放行
        if (check) {
            chain.doFilter(rq, rp);
            return;
        }
        //判断登录状态,如果已登录也放行
        if (rq.getSession().getAttribute("employee") != null) {
            BaseContext.setCurrentId((Long) rq.getSession().getAttribute("employee"));
            chain.doFilter(rq, rp);
            BaseContext.remove();
            return;
        }
        if (rq.getSession().getAttribute("user") != null) {
            BaseContext.setCurrentId((Long) rq.getSession().getAttribute("user"));
            chain.doFilter(rq, rp);
            BaseContext.remove();
            return;
        }

        //不登录返回NOTLOGIN
        rp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


    }

    //路径匹配
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    private boolean check(String[] loginUrls, String uri) {
        //判断是否放行
        for (String url : loginUrls) {
            boolean match = antPathMatcher.match(url, uri);
            if (match) {
                return true;
            }

        }
        return false;

    }


}
